// pages/user/add/index.js
const config = require("../../../utils/config.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dormNumber:'',
    name:'',
    phone:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },
  inputName(e) {
    this.setData({
      name:e.detail.value
    })
  },
  inputPhone(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  inputDormNumber(e) {
    this.setData({
      dormNumber: e.detail.value
    })
  },
  addUser(e) {
    console.log(e)
    let data = {
      name:this.data.name,
      phone:this.data.phone,
      dormNumber: this.data.dormNumber,
      headimg: e.detail.userInfo.avatarUrl
    }
    let superior = wx.getStorageSync("superior")
    if (superior != null && superior != '' && superior != undefined)
      data.superior = superior
    if (data.phone.trim() == '' || data.dormNumber.trim() == '' || data.name.trim() == '') {
      wx.showToast({
        title: '信息不能为空',
        icon: 'none'
      })
      return false;
    }

    //手机号正则
    var phoneReg = /(^1[3|4|5|7|8]\d{9}$)|(^09\d{8}$)/;
    //电话
    if (!phoneReg.test(data.phone.trim())) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return false;
    }

    // 宿舍号 5-109
    let scReg = /^\d+-\d{3}$/;
    if (!scReg.test(data.dormNumber.trim())) {
      wx.showToast({
        title: '宿舍格式不正确',
        icon: 'none'
      })
      return false;
    }
    wx.login({
      success(resCode) {
        data.code = resCode.code
        wx.request({
          url: config.HOST + '/user/reg',
          data: data,
          success: (res) => {
            if(res.data.status==200) {
              wx.showToast({
                title: '已注册,请登录！',
                duration: 5000,
                success() {
                  wx.navigateBack({})
                }
              })
              
            }else{
              wx.showToast({
                title: res.data.message,
                icon: 'none'
              })
            }
          }
        })
      }
    })
  }
})